package com.sbtr.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.sbtr.business.classify.entity.AlgorithmInfo;
import com.sbtr.business.classify.service.AlgorithmInfoService;
import com.sbtr.business.trainingtask.service.ITrainingInfoService;
import com.sbtr.common.PageDto;
import com.sbtr.common.Response;
import com.sbtr.controller.common.CommonController;
import com.sbtr.exception.BDException;
import com.sbtr.open.trainingtask.dto.TrainingInfoDto;
import com.sbtr.security.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 训练任务表 前端控制器
 * </p>
 *
 * @author wangwh15
 */
@RestController
@RequestMapping("/traininginfo/training-info")
@Api(tags = "模型任务训练接口（包含各类模型训练任务的管理、启动、训练等）")
public class TrainingInfoController extends CommonController<AlgorithmInfo, AlgorithmInfoService> {
    @Autowired
    private AlgorithmInfoService algorithmInfoService;

    @Autowired
    private ITrainingInfoService trainingInfoService;

    @Resource
    TaskExecutor taskExecutor;

    @Autowired
    RedisUtil redisUtil;
    String prefix_ip="train:ip:"+System.getenv("NODE_IP");

    @ApiOperation(value = "根据id查找", notes = "根据id查找", httpMethod = "GET")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Response<TrainingInfoDto> findById(@PathVariable("id") Long id) {
        return Response.success(trainingInfoService.findById(id));
    }

    @ApiOperation(value = "根据id删除", notes = "根据id删除", httpMethod = "DELETE")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Response<Boolean> deleteById(@PathVariable("id") Long id) {
        boolean b = trainingInfoService.deleteById(id);
        if (b) {
            return Response.success("删除成功", b);
        } else {
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败");
        }
    }

    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "GET")
    @RequestMapping(value = "search", method = RequestMethod.GET)
    public Response<PageDto<TrainingInfoDto>> search(
            @RequestParam(name = "taskName", required = false) String taskName, @RequestParam("page") Long currPage,
            @RequestParam("pageSize") Long pageSize,
            @RequestParam(name = "projectId", required = false) Long projectId) {
        return Response.success(trainingInfoService.search(taskName, currPage, pageSize, projectId));
    }


    @ApiOperation(value = "根据项目id去查询", notes = "根据项目id去查询", httpMethod = "GET")
    @RequestMapping(value = "getByProjectId", method = RequestMethod.GET)
    public Response<TrainingInfoDto> getByProjectId(
            @RequestParam(name = "projectId", required = false) Long projectId) {
        return Response.success(trainingInfoService.getByProjectId(projectId));
    }

//    @PostConstruct
//    public void init(){
//        List<TrainingInfo> list = trainingInfoService.list();
//
//        List<String> ips = new ArrayList<>();
//        ips.add("10.21.31.83");
//        ips.add("10.21.31.84");
//        ips.add("10.21.31.85");
//        ips.add("10.21.31.86");
//        ips.add("10.21.31.87");
//        ips.add("10.21.31.88");
//        ips.add("10.21.31.89");
//        ips.add("10.21.31.90");
//        Collections.shuffle(list);
//        Random random = new Random();
//        for (int i = 0; i < list.size(); i++) {
//            int n =  random.nextInt(8);
//            redisUtil.sSet("train:ip:"+ips.get(n),list.get(i).getId());
//        }
//    }


    @ApiOperation(value = "查询任务状态数量", notes = "查询任务状态数量", httpMethod = "GET")
    @RequestMapping(value = "getTrainingStatusList", method = RequestMethod.GET)
    public Response<List<Map<String,Object>>> getTrainingStatusList() {
//        Set<Object> list = redisUtil.sGet("train:ip:"+ip);
        Set<Object> list = redisUtil.sGet(prefix_ip);
        String ids = null;
        if(CollectionUtil.isNotEmpty(list)){
            ids=list.stream().map(String::valueOf).collect(Collectors.joining(","));
        }
        return Response.success(trainingInfoService.getTrainingStatusList(ids));
    }

    // 数据类任务开始start==
    @ApiOperation(value = "数据类任务启动", notes = "数据类任务启动", httpMethod = "POST")
    @RequestMapping(value = "/startTask", method = RequestMethod.POST)
    public Response<Boolean> startTask(Long id) {
        if(id==null){
            throw new BDException("id为空，请传id");
        }
        redisUtil.sSet(prefix_ip,id);
        return Response.success(trainingInfoService.startTask(id));
    }

    @ApiOperation(value = "停止数据类任务", notes = "停止数据类任务", httpMethod = "POST")
    @RequestMapping(value = "/{id}/stopTask", method = RequestMethod.POST)
    public Response<Boolean> stopTask(@PathVariable("id") Long id) {
        return Response.success(trainingInfoService.stopTask(id));
    }


    @ApiOperation(value = "保存", notes = "保存", httpMethod = "POST")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Response<Object> create(@RequestBody TrainingInfoDto dto) throws IOException {
        if (dto.getId() == null) {
            dto.setCreateTime(new Date());
            dto.setStatus(TrainingInfoDto.TASK_STATUS_NOTSTARTED);
        }
        if (dto.getTaskType() != null && dto.getTaskType() == 2) {
            List<Long> ids = trainingInfoService.createBath(dto);
//            for (int i = 0; i < ids.size(); i++) {
//                int finalI = i;
//                taskExecutor.execute(() -> {
//                    try {
//                        Thread.sleep((finalI * 10 + 2) * 1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    trainingInfoService.startTask(ids.get(finalI));
//                });
//            }
            return Response.success(ids);
        } else {
            TrainingInfoDto trainingInfoDto = trainingInfoService.create(dto);
            List<Long> ids = new ArrayList<>();
            ids.add(trainingInfoDto.getId());
//            redisUtil.sSet(prefix_ip,trainingInfoDto.getId());
//            trainingInfoService.startTask(trainingInfoDto.getId());
            return Response.success(ids);
        }

    }

//	// 数据类任务开始start==
//	@ApiOperation(value = "数据类任务启动", notes = "数据类任务启动", httpMethod = "POST")
//	@RequestMapping(value = "/{id}/getFileInfo", method = RequestMethod.POST)
//	public Response<FileDto> getFileInfo(@PathVariable("id") Long id) {
//		return Response.success(trainingInfoService.getFileInfo(id));
//	}

}

